<template>
  <view class="normal-login-container">
    <!-- 登录页面 logo 及标题 -->
    <view class="logo-content align-center justify-center flex">
      <image
          :src="globalConfig.appInfo.logo"
          mode="widthFix"
          style="width: 100rpx; height: 100rpx;"
      ></image>
      <text class="title">移动端登录</text>
    </view>

    <!-- 登录表单区域 -->
    <view v-if="!isWxLogin" class="login-form-content">
      <!-- 账号输入框 -->
      <view class="input-item flex align-center">
        <view class="iconfont icon-user icon"></view>
        <input
            v-model="loginForm.username"
            class="input"
            maxlength="30"
            placeholder="请输入账号"
            type="text"
        />
      </view>

      <!-- 密码输入框 -->
      <view class="input-item flex align-center">
        <view class="iconfont icon-password icon"></view>
        <input
            v-model="loginForm.password"
            class="input"
            maxlength="20"
            placeholder="请输入密码"
            type="password"
        />
      </view>

      <!-- 验证码输入框，仅在开启验证码时显示 -->
      <view
          v-if="captchaEnabled"
          class="input-item flex align-center"
          style="width: 60%; margin: 0px;"
      >
        <view class="iconfont icon-code icon"></view>
        <input
            v-model="loginForm.code"
            class="input"
            maxlength="4"
            placeholder="请输入验证码"
            type="number"
        />
        <view class="login-code">
          <image
              :src="codeUrl"
              class="login-code-img"
              @click="getCode"
          ></image>
        </view>
      </view>

      <!-- 登录按钮 -->
      <view class="action-btn">
        <button
            class="login-btn cu-btn block bg-blue lg round"
            @click="handleLogin"
        >
          登录
        </button>
      </view>
    </view>
	
	<view v-if="isWxLogin" class="login-form-content">
		<!-- 登录按钮 -->
		<view class="action-btn">
		  <button
		      class="login-btn cu-btn block bg-blue lg round"
		      @click="handleWxLogin"
		  >
		    一键登录
		  </button>
		</view>
	</view>

    <!-- 协议说明区域 -->
    <view class="xieyi text-center">
      <text class="text-grey1">登录即代表同意</text>
      <text class="text-blue" @click="handleUserAgrement">《用户协议》</text>
      <text class="text-blue" @click="handlePrivacy">《隐私协议》</text>
    </view>
  </view>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {getCodeImg} from '@/api/login'
import {useUserStore} from '@/store/modules/user'

const loginForm = reactive({
  username: '',
  password: '',
  loginType: '',
  code: '',
  uuid: ''
})
const globalConfig = getApp().globalData.config
const codeUrl = ref('')
const captchaEnabled = ref('')
const isWxLogin = ref(false)

const instance = getCurrentInstance()
const proxy = instance.proxy
const userStore = useUserStore()
onMounted(() => {
	const token = userStore.token
	console.log('当前token:', token)
	if (token) {
	  console.log('检测到token，开始验证有效性')
	  userStore.verifyToken().then(valid => {
		console.log('token验证结果:', valid)
		if (valid) {
		  console.log('token有效，跳转至首页')
		  proxy.$tab.reLaunch('/pages/index')
		} else {
		  console.log('token无效，显示登录界面')
		  getCode()
		}
	  }).catch(error => {
		console.error('token验证失败:', error)
		getCode()
	  })
	} else {
	  console.log('未检测到token，显示登录界面')
	  getCode()
	}
	if(isWxLogin){
		checkAuthCode();
	}
})

// 检查URL中的code
const checkAuthCode= () => {
      const urlParams = new URLSearchParams('?'+window.location.href.split('?')[1]);
      const code = urlParams.get('code');
      if (code) {
		  console.log(code)
        loginWithCode(code);
      }
}

// 调用后台登录接口
const loginWithCode = async (code) => {
	try{
		uni.showLoading({ title: '登录中...', mask: true });
		const result = await userStore.login({
			code: code,
			loginType: 'QWX_MIMI'
		})
		await userStore.getUserInfo()
		proxy.$tab.reLaunch('/pages/index')
		uni.hideLoading();
	} catch (error) {
	    window.location.href = "#"
	}
	
}
	
	

// 处理隐私协议的点击事件
const handlePrivacy = () => {
  const site = globalConfig.appInfo.agreements[0]
  proxy.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
}


// 处理用户协议的点击事件
const handleUserAgrement = () => {
  const site = globalConfig.appInfo.agreements[1]
  proxy.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
}

// 获取图形验证码
const getCode = () => {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = 'data:image/gif;base64,' + res.img
      loginForm.uuid = res.uuid
    }
  })
}

const handleLogin = async () => {
  if (loginForm.username === '') {
    proxy.$modal.msgError('请输入您的账号')
  } else if (loginForm.password === '') {
    proxy.$modal.msgError('请输入您的密码')
  } else if (loginForm.code === '' && captchaEnabled.value) {
    proxy.$modal.msgError('请输入验证码')
  } else {
    proxy.$modal.loading('登录中，请耐心等待...')
    loginForm.loginType = 0
    pwdLogin()
  }
}

const handleWxLogin = async () => {
	
	const authUrl = `http://jstxwx.cnpc.com.cn:10082/connect/oauth2/authorize?
	  appid=wl6e538311bc&
	  redirect_uri=`+encodeURIComponent(window.location.href)+`&
	  response_type=code&
	  scope=snsapi_base&
	  agentid=1001094&
	  state=STATE#wechat_redirect`;
	window.location.href = authUrl.replace(/\s+/g, ''); // 去除空格
}



const pwdLogin = async () => {
  try {
    await userStore.login(loginForm)
    proxy.$modal.closeLoading()
    loginSuccess()
  } catch (error) {
    if (captchaEnabled.value) {
      getCode()
      loginForm.code = ''
    }
  }
}

const loginSuccess = async () => {
  try {
    await userStore.getUserInfo(); // 确保获取用户信息完成
    proxy.$modal.closeLoading(); // 关闭加载状态
    proxy.$tab.reLaunch('/pages/index'); // 跳转到首页
  } catch (error) {
    console.error('获取用户信息失败:', error);
    proxy.$modal.closeLoading(); // 确保加载状态关闭
    proxy.$modal.msgError('登录失败，请重试'); // 提示用户登录失败
  }
};
</script>

<style lang="scss">
// 页面整体背景颜色
page {
  background-color: #ffffff;
}

// 正常登录容器样式
.normal-login-container {
  width: 100%;

  // 登录页面的 logo 与标题部分
  .logo-content {
    width: 100%;
    font-size: 21px;
    text-align: center;
    padding-top: 15%;

    image {
      border-radius: 4px;
    }

    .title {
      margin-left: 10px;
    }
  }

  // 登录表单内容区域
  .login-form-content {
    text-align: center;
    margin: 20px auto;
    margin-top: 15%;
    width: 80%;

    // 输入项样式
    .input-item {
      margin: 20px auto;
      background-color: #f5f6f7;
      height: 45px;
      border-radius: 20px;

      .icon {
        font-size: 38rpx;
        margin-left: 10px;
        color: #999;
      }

      .input {
        width: 100%;
        font-size: 14px;
        line-height: 20px;
        text-align: left;
        padding-left: 15px;
      }
    }

    // 登录按钮样式
    .login-btn {
      margin-top: 40px;
      height: 45px;
    }

    // 协议说明区域样式
    .xieyi {
      color: #333;
      margin-top: 20px;
    }

    // 验证码图片区域样式
    .login-code {
      height: 38px;
      float: right;

      .login-code-img {
        height: 38px;
        position: absolute;
        margin-left: 10px;
        width: 200rpx;
      }
    }
  }
}
</style>
